import { App } from './app';
import './dx-ext';
import './qrcode';
import './order';
import './data';
import './product';
import './daily';
import './dealer';

jQuery.extend({
	crudStoreResp: null,

	crudStore: function(url, options) {

		var SERVICE_URL = url;
		options = $.extend({
			onDataArrived: function(data) {
				return data;
			}
		}, options);

		return new DevExpress.data.CustomStore($.extend({}, options, {

			load: function(loadOptions) {

				var u = new Url(SERVICE_URL);

				u.query._param = JSON.stringify(loadOptions);

				return $.getJSON(u).then(function(resp) {
					console.log("data done");
					return options.onDataArrived(resp);
				});
			},

			byKey: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.getJSON(u).then(function(resp) {
					return resp.data;
				});
			},

			insert: function(values) {
				return $.post(SERVICE_URL, values).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			update: function(key, values) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "PUT",
					data: values,
				}).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			remove: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "DELETE"
				});
			}

		}));
	},

	crud: function(options) {
		if(typeof(options) === 'object') {
			var app = options.app,
				route = options.route,
				store = jQuery.crudStore(options.url || API(route), options.store);

			options.search = $.extend({
				mobile: 'mobile',
				name: 'uname',
				dateA: 'dateA'
			}, options.search);

			// list

			app.get('#/' + route, function() {
				var eventContext = this,
					capable = $.extend({
						create: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-list").html(), $.extend({}, options, {
					capable: capable
				}))).dxInit();

				var gridType = options.gridType || "dxDataGrid";

				if(options.buttons) {
					$.each(options.buttons, function(i, button) {
						button.instance = $("<div>").dxButton($.extend({
							type: 'normal',
							onClick: function(e) {
								var selections = [];

								if(options.onGetSelectedRowsData) {
									selections = options.onGetSelectedRowsData.call(eventContext, $("#content .crud-grid"));
								} else if(!options.onRenderGrid) {
									selections = $("#content .crud-grid")[gridType]('getSelectedRowsData');
								}

								button.onRoute && button.onRoute.call(eventContext, e.component, selections);
							}
						}, button)).appendTo(
							$("#content .crud-buttons")).dxButton('instance');
					});
				}

				var defaultToolbarItems = [];
				if(options.capable.create) {
					defaultToolbarItems.push('create');
				}

				var toolbarOptions = options.toolbar ? options.toolbar : {
					items: defaultToolbarItems
				};

				$.each(toolbarOptions.items, function(i, item) {
					if(item === 'create') {
						toolbarOptions.items[i] = {
							location: 'before',
							widget: 'dxButton',
							options: {
								text: '新建',
								onClick: function() {
									eventContext.redirect('#/' + route + '/edit');
								}
							}
						};
					}
				});

				console.log(toolbarOptions);
				$("#content .toolbar").dxToolbar(toolbarOptions);

				var ds = new DevExpress.data.DataSource({
					store: store
				});

				if(eventContext.params) {
					$.each(eventContext.params, function(k, v) {
						if(typeof(v) !== 'function' && typeof(v) !== 'object') {
							ds.filter(k, '=', v);
						}
					});
				}

				var param = {
					dataSource: ds,
					allowColumnResizing: true,
					selection: {
						mode: "multiple",
						showCheckBoxesMode: 'always',
						selectAllMode: 'page'
					},
					remoteOperations: true,
					paging: {
						pageSize: 10,
						pageIndex: 0
					},
					onSelectionChanged: function(e) {
						$.each(options.buttons, function(i, button) {
							button.onSelectionChanged &&
								button.onSelectionChanged.call(eventContext, button.instance, e.selectedRowsData, e.component);
						});
					}
				};

				if(options.columns) {
					for(var i = 0; i < options.columns.length; i++) {
						if(options.columns[i].buttons) {

							options.columns[i].cellTemplate = (function(buttons) {
								return function(container, ei) {

									$.each(buttons, function(i, button) {
										var title = button.title,
											url = '#';

										if(button.url) {
											url = Mustache.render(button.url, ei.data);
										}

										var el = $(Mustache.render('<a style="margin: 0 10px;" href="{{url}}">{{title}}</a>', {
											title: title,
											url: url
										}));

										if(button.onClick) {
											el.click(function() {

												button.onClick(ei.data, ei.component);
												return false;
											});
										}

										el.appendTo(container);

										if(button.del) {

											$("<span style='margin:0 5px;vertical-align:1px'>|</span>").appendTo(container)

											$("<a>").text("删除").click(function() {

												DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(sele) {

													if(sele) {
														var getId = ei.data.id

														$.ajax({
															type: "delete",
															url: $.config('apiUrl') + "restful/" + getId + "?_model=" + button.del
														}).then(function(a) {

															if(a.status = "success") {

																DevExpress.ui.notify({
																	message: function() {

																	let	gridComponent = $("#content .crud-grid").dxDataGrid('instance');

																		gridComponent.option('dataSource').load();

																		return "成功删除";
																	}
																}, "success", 1000)

															} else {

																DevExpress.ui.notify({

																	message: function() {

																		return "操作失败";
																	}
																}, "warning", 1000)
															}
														})
													}
												})
											}).appendTo(container)

										}

									});
								};
							})(options.columns[i].buttons);
						}
					}
					param['columns'] = options.columns;
				}

				if(options.onRenderGrid) {
					options.onRenderGrid.call(eventContext, $("#content .crud-grid"), $.extend({}, param, options.grid));
				} else {
					$("#content .crud-grid")[gridType]($.extend({}, param, options.grid));
				};

				// var gridInst = $("#content .crud-grid")[gridType]("instance");

				if(!options.search['mobile']) $("#content [data-search=mobile]").closest(".input-group").hide();
				if(!options.search['name']) $("#content [data-search=name]").closest(".input-group").hide();
				if(!options.search['lookup']) $("#content [data-search=lookup]").closest(".lookup").hide();
				if(!options.search['mobile'] && !options.search['name']) {
					$("#content .grid-search").hide();
				}

				var now = new Date()
				$("#date").dxDateBox({
					type: "date",
					value: now,
					displayFormat: 'yyyy-MM-dd',
					dateSerializationFormat: "yyyy-MM-dd",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd'
					}
				})

				$("#content .grid-search").click(function() {
					var name = $("#content [data-search=name]").val(),
						mobile = $("#content [data-search=mobile]").val(),
						dateA = $("#content #date").dxDateBox('option', 'value');

					if(name) {
						ds.searchExpr(options.search['name']);
						$("#content [data-search=mobile]").val('');
					} else if(mobile) {
						ds.searchExpr(options.search['mobile']);
						$("#content [data-search=name]").val('');
					} else if(dateA) {
						ds.searchExpr(options.search['dateA']);
						$("#content #date").dxDateBox('option', 'value');
					}

					ds.searchOperation("contains");
					ds.searchValue(name || mobile || dateA);
					ds.reload();
				});


				// $("#modify_pwd", $(this)).dxDataGrid(param);
				
			});

			function initCrudForm($c, context) {
				var id = context.params.id,
					formOptions = {
						readOnly: false,
						showColonAfterLabel: true,
						showValidationSummary: false,
						colCount: 1,
						validationGroup: "crud",
						items: [],
						onFieldDataChanged: function(e) {
							// console.log("onFieldDataChanged");
							// console.log(e);
						}
					};

				if(id) {
					formOptions.onContentReady = function(e) {
						store.byKey(id).then(function(resp) {

							if(options.form.beforeDataUpdate) {
								options.form.beforeDataUpdate(form, {
									data: resp
								});
							}
							e.component.option('formData', resp);

							if(options.form.afterDataUpdate) {
								options.form.afterDataUpdate(form, {
									data: resp
								});
							}
						});
					}
				}

				var items = [];
				if(options.form && options.form.items) {
					var scene = (id ? 'edit' : 'create');
					$.each(options.form.items, function(i, item) {
						if(item.scene && $.inArray(scene, item.scene) < 0) {

						} else {
							items.push(item);
						}
					});
				}

				var form = $("#form", $c).dxForm($.extend(formOptions, options.form, {
					items: items
				})).dxForm('instance');

				$("#form-container #save", $c).click(function() {
					var result = form.validate();

					if(!result.isValid) {
						var $el = result.validators[0].element();

						var offset = $el.offset();

						$('html, body').animate({
							scrollTop: offset.top - $("header.app-header").height() - 20
						});

					} else {
						$("#form-container", $c).submit();
					}

					return false;
				});

				$("#form-container", $c).on("submit", function(e) {
					var bs = true;
					if(options.form.beforeSubmit) {
						bs = options.form.beforeSubmit(form, id);
					}

					$.when(bs).then(function(result) {
						if(result) {
							if(id) {
								store.update(id, form.option('formData')).then(function(values, resp) {
									DevExpress.ui.notify({
										message: "已更新",
									}, "success", 1000);
									if(options.form.onSaved) {
										options.form.onSaved.call(context, values, resp);
									} else {
										context.redirect('#/' + route);
									}
								}).fail(function() {
									DevExpress.ui.notify({
										message: $.crudStoreResp.message
									}, "warning", 2000);
								});
							} else {
								store.insert(form.option('formData')).then(function(values, resp) {
									if(resp.status == "error") {
										DevExpress.ui.dialog.alert(resp.msg, '提示');
										return false;
									} else {
										DevExpress.ui.notify({
											message: "已完成",
										}, "success", 1000);
										context.redirect('#/' + route);
										//		        						context.redirect('#/' + route + '/edit/' + resp.model.id);
									}
								}).fail(function(resp) {
									DevExpress.ui.notify({
										message: resp,
									}, "warning", 2000);
								});
							}
						}
					})

					return false;
				});

				$("#form-container .delete", $c).click(function() {
					DevExpress.ui.dialog.confirm("确认删除吗?", "请确认").done(function(dialogResult) {
						if(dialogResult) {

							store.remove(id).then(function(resp) {

								DevExpress.ui.notify({
									message: "已删除",
								}, "success", 1000);
								context.redirect("#/" + route);
							});
						}
					});

					return false;
				});

				$("#form-container #cancel").click(function() {
					context.redirect("#/" + route);
					return false;
				});

				var saveNext = false;
				$("#form-container #save").click(function() {
					saveNext = false;
					return false;
				});
				$("#form-container #save-next").click(function() {
					saveNext = true;
					return false;
				});
			}

			// create or edit
			//			console.log("add crud " + route + "/edit");

			app.get('#/' + route + "/edit", function() {
				var eventContext = this,
					capable = $.extend({
						saveNext: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '新建'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});

			//			console.log("add crud " + route + "/edit/:id");

			app.get('#/' + route + "/edit/:id", function() {
				var eventContext = this,
					capable = $.extend({
						delete: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '编辑'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});
		}
	},

	dxCall: function() {
		var comp = $(this).data('dxComponents');
		if(comp && comp.length) {
			var inst = $(this)[comp[0]]("instance");

			return inst[arguments[0]].apply(inst, arguments.slice(1));
		} else {
			return undefined;
		}
	}
});

App.registerCrud({
	route: 'product',
	url: API('restful?_model=product'),
	title: '产品',
	placeholder: '产品名称',
	capable: {
		create: true
	},
	grid: {
		selection: {
			mode: 'none'
		},
		columnAutoWidth:true,
		showRowLines:true,
		wordWrapEnabled:true
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '新建',
				onClick: function() {
					App.getEventContext().redirect('#/product/edit');
				}
			}
		}]
	},
	search: {
		name: 'chname',
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chname',
			caption: '产品名称'
		}, {
			dataField: 'weight',
			caption: '权重',
			cellTemplate: function(con, da) {
				$(con).dxWeight("product", da)
			}
		}, {
			dataField: 'online',
			caption: '上下线',
			cellTemplate: function(con, opt) {
				$(con).dxUpdown('product', opt)

			}
		}, {
			minWidth: 100,
			caption: '操作',
			buttons: [{
				title: '编辑',
				// url: '#/newproduct/{{id}}',
				url:'#/product/edit/{{id}}',
				del: 'product'
			}]

		},
		{
			caption: 'id',
			caption:"产品价格",
			buttons: [{
				title: "查看",
				url:'#/price?id={{id}}'
				
			}]
		}, {
			dataField: 'pv',
			caption: 'pv'
		}, {
			dataField: 'uv',
			caption: 'uv'
		}, {
			dataField: 'collect_count',
			caption: '收藏量'
		}, {
			dataField: 'order_count',
			minWidth: 100,
			caption: '订单量'
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		beforeSubmit:function(form,id){
			let formData =form.option('formData');
			formData.is_hot = formData.is_hot?1:0;
			form.option('formData',formData)
			return true
		},
		colCount: 1,
		items: [{
			itemType: "group",
			items: [{
				dataField: "chname",
				label: {
					text: '产品名称'
				},
				validationRules: [{
					type: "required",
					message: "请输入产品名称"
				}]
			},{
				dataField:'attr_group_id',
				label:{text:'产品属性'},
				editorType:'dxSelectBox',
				editorOptions:{
				dataSource:$.crudStore(API('restful?_model=product-attr-group')),
				valueExpr:'id',
				searchEnabled: true,
                displayExpr: 'name'
				}
			},{
				dataField:'category_id',
				label:{text:'分类'},
				editorType:'dxSelectBox',
				editorOptions:{
					dataSource:[{name:'车载',id:1},{name:'家用',id:2}],
					placeholder: "分类",
					searchEnabled: true,
					valueExpr: 'id',
					displayExpr: 'name',
					noDataText: '没有请求到分类数据',
					deferRendering: false,
					itemTemplate: function(data) {
						return data.name
					}
				}
			},{
				dataField:"is_hot",
				label:{text:'设置热销'},
				editorType:'dxCheckBox'
			},{
				dataField:'banner',
				label:{text:'列表图'},
				editorType:'imagesdetail',
				editorOptions:{
					single:true
				}
			},{
				dataField:'covers',
				label:{text:'详情轮播图'},
				editorType:'imagesdetail'
			},{
				dataField:'detail',
				label:{text:'产品详情'},
				editorType:'imagesdetail'
			},{
				dataField:'param',
				label:{text:'产品参数'},
				editorType:'imagesdetail'
			}]
		}]
	}

});


var  user_search_name =''

App.registerCrud({
	url: API('restful?_model=user'),
	route: 'user_list',
	title: '用户',
	capable: {
		create: false,
		delete: false
	},
	search:{
		mobile:'mobile',
		name:'name'
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '请输入用户姓名或手机号',
				onInitialized: function(e) {
					user_search_name = e.component;
				}
			}
		},{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '搜索用户',
				onClick: function() {
					var ds = App.crudGridInstance().option('dataSource');

					ds.searchExpr(['name', 'mobile']);
					ds.searchValue(user_search_name.option('value'));

					ds.reload();
				}
			}
		}]
	},
	grid:{
		selection: {
			mode: 'none'
		}
	},
	columns: [{
		dataField: 'id',
		caption: 'id',
		width:80
	}, {
		dataField: 'name',
		caption: '姓名',
		width:200
	}, {
		dataField: 'mobile',
		caption: '联系方式',
		width:150
	}, {
		dataField: 'bonus_total',
		caption: '总分红'
	}, {
		dataField: 'parent_name',
		caption: '邀请人'
	}, {
		dataField: 'order_count',
		caption: '产品购买次数'
	},{
		dataField:'is_dealer',
		caption:'设置经销商',
		cellTemplate:function($c,d){
			let ast = d.value,
			state = 'active',
			text = '设置经销商'
			if(ast){
			state = 'stop'
			text = '取消经销商'
			}
	$('<a>').click(function(){

		$.ajax({
			url:API('dealer/change'),
			type:'post',
			data:{userIds:d.row.data.id,state:state},
			headers:{'Authorization':"bearer " + localStorage.accessToken},
			success:function(res){
				if(res.data.success === 0){
					DevExpress.ui.notify(res.data.errors[0],'warning',1500)
				}else{
					var ds = App.crudGridInstance().option('dataSource');
					ds.reload()
					DevExpress.ui.notify(text+'操作成功','success',1500)
				}
			},
			error:function(){
				DevExpress.ui.notify('未知错误，请重试','warning',1500)
				console.error('dealer/change')
			}
		})

	}).text(text).appendTo($c)
		

		}
	}]
});

let complete_list_filter=''
App.registerCrud({
	url: API('restful?_model=user-withdraw'),
	route: 'complete',
	title: '用户',
	capable: {
		create: false,
		delete: false
	},
	search:{
		mobile:'mobile',
		name:'name'
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '请输入用户姓名或手机号',
				onInitialized: function(e) {
					complete_list_filter = e.component;
				}
			}
		},{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '搜索用户',
				onClick: function() {
					var ds = App.crudGridInstance().option('dataSource');
					ds.searchExpr(['username', 'mobile']);
					ds.searchValue(complete_list_filter.option('value'));
					ds.reload();
				}
			}
		},{
			location:'before',
			widget:'dxSelectBox',
			options:{
				dataSource:[{value:'',text:'所有'},{value:0,text:'待审核'},{value:1,text:'已审核'},{value:2,text:'已提现'},{value:3,text:'已拒绝'}],
				displayExpr:'text',
				valueExpr:'value',
				value:'',
				onValueChanged:function(e){
					var ds = App.crudGridInstance().option('dataSource');
					if(e.value||e.value === 0){
						ds.filter(['state','=',e.value])
					}else{
						ds.filter(null)
					}
				
					ds.reload();
				}
			}
		}]
	},
	grid:{
		selection: {
			mode: 'none'
		}
	},
	columns: [{
		dataField: 'username',
		caption: '用户昵称',
		width:200
	}, {
		dataField: 'mobile',
		caption: '联系方式',
		width:150
	}, {
		dataField: 'request_time',
		caption: '请示时间'
	} ,{
		dataField: 'card_bank',
		caption: '提现银行',
		cellTemplate:function($c,d){
			let data =d.row.data;
			$('<div/>').text(data.card_bank).appendTo($c)
			$('<div/>').text(data.bank_subbranch_name).appendTo($c)
			$('<div/>').text(data.card_number).appendTo($c)
		}
	}, {
		dataField: 'card_username',
		caption: '帐号姓名'
	}, {
		dataField: 'request_amount',
		caption: '提现额度'
	}, {
		dataField: 'remark',
		caption: '备注'
	},{
		dataField:'state',
		caption:'状态',
		cellTemplate:function($c,d){
			let text = '';
			switch(d.value){
				case 0:text='待审核';break;
				case 1:text='已审核';break;
				case 2:text='已提现';break;
				case 3:text='已拒绝';break;
			}
		$c.text(text)
		}
	},{
		dataField:"state",
		caption:'审核',
		cellTemplate:function($c,d){
			function fa(state){
			let remark = prompt('请输入备注');
			if(remark){
				let data = {
					ids:d.row.data.id,
					remark,
					state
				}
				$.ajax({
					url:API('withdraw/change'),
					data,
					method:"post",
					headers: {
				Authorization: "bearer " + localStorage.accessToken
					},
					success:function(resp){
						if(resp.status == 'success'){
							let ds = App.crudGridInstance().option('dataSource');
							ds.reload()
							DevExpress.ui.notify('操作成功','success',1500)
						}else{
							DevExpress.ui.notify('操作失败:'+resp.message,'warning',1500)
						}
					},
					error:function(err){
						DevExpress.ui.notify('操作失败','warning',1500)
					}
				})
				}
			}
			if(d.value === 0){
				$('<a/>').text('通过').click(function(){
					fa('pass')
				}).appendTo($c)

				$('<span/>').text(' | ').css('margin','0 3px').appendTo($c)

				$('<span/>').text('拒绝').click(function(){
					fa('refuse')
				}).appendTo($c)
				
			}
		}
	},{
		caption:'打款确认',
		dataField:"id",
		cellTemplate:function($c,d){
			if(d.row.data.state===1){
				$('<a/>').text('确认打款').click(function(){
					if(confirm('是否确认打款')){
						$.ajax({
							url:API('withdraw/complete'),
							data:{ids:d.value},
							method:"post",
							headers: {
								Authorization: "bearer " + localStorage.accessToken
									},
							success:function(resp){
								if(resp.status == 'success'){
									let ds = App.crudGridInstance().option('dataSource');
									ds.reload()
									DevExpress.ui.notify('操作成功','success',1500)
								}else{
									DevExpress.ui.notify('操作失败：'+resp.message,'warning',1500)
								}
							},
							error:function(err){
								DevExpress.ui.notify('操作失败','warning',1500)
							}	
						})
					}
				}).appendTo($c)
			}
		}
	}]
});

App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users',
	title: '系统管理员',
	placeholder: '会员名',
	capable: {
		create: true
	},
	buttons: [{
		text: '删除',
		type: 'danger',
		disabled: true,
		onSelectionChanged: function(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		onClick: function() {
			var store = $.crudStore(API("admin")),
				gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
				selections = gridComponent.getSelectedRowsData(),
				ids = $.map(selections, function(item) {
					return item.id;
				}).join(",");

			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(dialogResult) {
				if(dialogResult) {
					store.remove(ids).then(function(resp) {

						DevExpress.ui.notify({
							message: "已删除",
						}, "success", 1000);
						gridComponent.option('dataSource').load();
					});
				}
			});
			return false;
		}
	}],
	columns: [{
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'account',
		caption: '账号'
	}, {
		dataField:'userType',
		caption:'权限',
		cellTemplate:function($c,d){
		
			var text = '';
			if(d.value == 'admin'){
			text = '管理员'
			}else if(d.value == 'editor'){
				text = '录入员'
			};
			$c.text(text)
		}
	},{
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/admin-users/edit/{{id}}'
		}, {
			title: '更改密码',
			url: '#/admin-users/password/edit/{{id}}'
		}, {
			title: '删除',
			onClick: function(data) {
				DevExpress.ui.dialog.confirm("确定删除 " + data.account + " 吗?", "请确认").done(function(dialogResult) {
					if(dialogResult) {
						var ds = App.crudGridInstance().option('dataSource');
						ds.store().remove(data.id).then(function(resp) {
							DevExpress.ui.notify({
								message: "已删除",
							}, "success", 1000);
							ds.reload();
						});
					}
				});
			}
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			dataField: 'name',
			label: {
				text: '名称'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField:'userType',
			editorType:'dxSelectBox',
			label:{text:'权限'},
			validationRules: [{
				type: "required"
			}],
			editorOptions:{
				dataSource:[{name:'管理员',value:'admin'},{name:'产品录入员',value:'editor'}],
				displayExpr:'name',
				valueExpr:"value",
				onValueChanged:function(e){
					App.getFormInstance().option('formData.userType',e.value)
				}
			}
		},{
			label: {
				text: '允许访问ip段'
			}
		}, {
			dataField: 'ip_min',
			label: {
				text: '最小值'
			}
		}, {
			dataField: 'ip_max',
			label: {
				text: '最大值'
			}
		}]
	}
});



App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users/password',
	title: '更改密码',
	capable: {
		create: false,
		delete: false
	},
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		onSaved: function() {
			this.redirect("#/admin-users");
		},
		items: [{
			dataField: 'name',
			label: {
				text: '用户名'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}]
	}
});

App.registerCrud({
	url: API('restful?_model=focus-picture'),
	route: 'banner',
	title: '焦点图',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'pic',
		caption: '图片',
		cellTemplate: function(c, ci) {
			$("<img src='" + ci.data.pic + "?imageView2/0/h/60'/>").appendTo(c);
		}
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'title',
		caption: '标题'
	}, {
		dataField: 'type',
		caption: '类型',
		cellTemplate: function(c, ci) {
			c.html(ci.data.type === 'article' ? '其他' : '产品');
		}
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate: function(con, da) {
			$(con).dxWeight("focus", da);
		}
	}, {
		caption: '操作',
		cellTemplate: function(con, dat) {
			$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function() {
				App.getEventContext().redirect('#/banner/edit/' + dat.data.id);
				return false;
			}).appendTo($(con));

			$(con).dxDelete('focus-picture', dat)
		}
	}],
	form: {
		beforeDataUpdate: function(formInstance, e) {
			e.data.obj_id = parseInt(e.data.obj_id);
		},
		items: [{
			dataField: 'title',
			label: {
				text: '标题'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'pic',
			label: {
				text: '封面图片'
			},
			editorType: 'ImageUploader',
			editorOptions: {
				single: true,
				imageWidth: 750,
				imageHeight: 608
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'type',
			label: {
				text: '类型'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxRadioGroup',
			editorOptions: {
				layout: "horizontal",
				valueExpr: 'value',
				dataSource: [{
					text: '其他',
					value: 'article'
				}, {
					text: '产品',
					value: 'product'
				}],
				onValueChanged: function(e) {
					var formInstance = App.getFormInstance();

					// formInstance.updateData({obj_id: 0});

					if(e.value === 'article') {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('restful?_model=cms-article'))
						});
					} else {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('restful?_model=wine-product'))
						});
					}
				}
			}
		}, {
			dataField: 'obj_id',
			label: {
				text: '产品'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=product')),
				showClearButton: true,
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到数据',
				itemTemplate: function(data, index, $el) {
					if(data && data.chname && data.name) {
						$("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
					} else if(data && data.title) {
						$("<span>" + data.title + "</span>").appendTo($el);
					}
				},
				displayExpr: function(data) {
					if(data && data.chname && data.name) {
						return data.chname + " (" + data.name + ")";
					} else if(data && data.title) {
						return data.title;
					} else {
						return "";
					}
				}
			}
		}]
	}
});






$(function() {

    let initApp = () => {
        var app = $.sammy('#content', function() {
            var app = this;

            console.log("handle routes");
            console.log(App.routes);

            $.each(App.routes, function(i, route) {
                var m = route.name.match(/[^\/]*/);
                app.get('#/' + route.name, function() {

                    var eventContext = this;

                    route.onLoad && route.onLoad.call(route, eventContext, $('#content'));

                    // $.get('template/' + m[0] + '.html', function(resp) {
                    //  $('#content').html(resp).dxInit();
                    //  $("#content").trigger("route.loaded", [eventContext])
                    // });
                });
            });

            // for(var i = 0; i < routes.length; i++) {
            //  (function(route) {
            //      var m = route.match(/[^\/]*/);
            //      app.get('#/' + route, function() {

            //          var eventContext = this;

            //          $.get('template/' + m[0] + '.html', function(resp) {
            //              $('#content').html(resp).dxInit();
            //              $("#content").trigger("route.loaded", [eventContext])
            //          });
            //      });
            //  })(routes[i]);
            // }

            console.log("handle pages");
            console.log(App.pages);
            $.each(App.pages, function(i, page) {
                $.crud($.extend({
                    app: app
                }, page));
            })

        });

        app.bind('changed', {}, function() {
            App.setEventContext(this);
        });
        app.run('#/product');
    }

    if (!localStorage.accessToken) {
		window.location.href = 'login.html';
		return;
	} else {
		$.ajax({
			headers: {
				Authorization: "bearer " + localStorage.accessToken
			},
			url: API('auth/me'),
			type: 'get',
			success: function(resp) {
				$(".app").show();

				var data = resp.data,
					type = data.userType;
				// if (data.userType === 'super' && data.account === 'admin') {
				// 	type = 'super';
				// }
				App.login(data);
console.log(resp)
				$(".admin-name").text(data.name);
				$(".auth-" + type).show();


				initApp();
			},
			error: function(resp) {
				window.location.href = 'login.html';

			}
		});
	}


    DevExpress.viz.currentTheme("generic.light");

    $("body").dxInit();

});